package cn.yunyichina.provider.message.sdk.app;

import cn.jpush.api.JPushClient;
import cn.jpush.api.common.resp.APIConnectionException;
import cn.jpush.api.common.resp.APIRequestException;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.audience.AudienceTarget;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import cn.yunyichina.provider.iface.entity.ErrorCodeDefine;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.LoggerFactory;


public class JpushMessage {
    private static org.slf4j.Logger logger = LoggerFactory.getLogger(JpushMessage.class);

    private static final String appKey = "d71839f014772337bc5e35bb";
    private static final String masterSecret = "46ba514f16dee38682cc5ef6";


    public static JPushClient jpushClient = new JPushClient(masterSecret, appKey, 3);

    /**
     * 发送推送
     * @param alias 用户号,user_id
     * @param notice 通知的内容(无则表示不用)
     * @param msg 消息的内容,异常时返回null
     */
    public static JSONObject sendPush(String alias, String notice, String msg) {

        try {
			//test json的长度，是否超过100字节
			JSONObject jsonObject = sendAndroidPush(alias, msg); //android走后台发送的形式

			//IOS走APN消息的形式 + 后台推送
			if (notice == null) {
			    notice = "消息";
			}
			if(jsonObject != null && Integer.valueOf(jsonObject.get("errcode").toString()) == 0){
			    sendIosPush(alias, msg, msg);
			    return jsonObject ;
			}else {
			    jsonObject = sendIosPush(alias, msg, msg);
			    return jsonObject;
			}
		} catch (NumberFormatException e) {
			logger.error("sendPush发送消息错误：\n");
			logger.error(ErrorCodeDefine.getStackTrace(e));
		}
        return null;
    }

    //调用极光接口发送消息
    private static JSONObject sendAndroidPush(String alias, String msg) {
        // For push, all you need do is to build PushPayload object.
        PushPayload payload = buildAndroidPushObject(alias, msg);
        payload.resetOptionsTimeToLive(0);//离线不保存
        JSONObject jsonObject = new JSONObject();
        try {
            PushResult result = jpushClient.sendPush(payload);
            logger.info("Got result - " + result);
            jsonObject.put("errcode", 0);
        } catch(APIConnectionException e) {
            logger.error("Connection error. Should retry later. ", e);

        } catch(APIRequestException e) {
            jsonObject.put("errcode", e.getErrorCode());
            jsonObject.put("errmsg", e.getErrorMessage());
            if("1011".equals(e.getErrorCode())){
                logger.error("用户[" + alias + "]在极光没有登记Android别名,不用放弃处理");
            }else {
                logger.warn("Error response from JPush server. Should review and fix it. " //
                        + "\nHTTP Status: " + e.getStatus()//
                        +"\nError Code: " + e.getErrorCode()//
                        +"\nMsg ID: " + e.getMsgId()//
                        +"\nError Message: " + e.getErrorMessage() +//
                        "\n"+e);
            }

        }
        return jsonObject;
    }

    //构建android的消息
    public static PushPayload buildAndroidPushObject(String alias, String msg) {
        logger.info("----推送消息给Android:alias =" + alias + ",内容= " + msg);

        return PushPayload//
                .newBuilder()//
                .setPlatform(Platform.android())//
                .setAudience(Audience.newBuilder()//
                        //.addAudienceTarget(AudienceTarget.tag("android"))//
                        .addAudienceTarget(AudienceTarget.alias(alias))//
                        .build())//
                .setMessage(Message.newBuilder()//
                        .setMsgContent(msg)//
                        .addExtra("from", "JPush")//
                        .build())//
                .build();

    }

    //XXX: IOS push

    //调用极光接口发送ios消息
    private static JSONObject sendIosPush(String alias, String alert, String msg) {
        logger.info("----推送消息给IOS:alias=" + alias + ",内容= " + msg);
        JSONObject jsonObject = new JSONObject();
        PushPayload payload = buildIosPushObject(alias, alert, msg);
//        payload.resetOptionsTimeToLive(0);//离线不保存

        try {
            PushResult result = jpushClient.sendPush(payload);
            logger.info("ios Got result - " + result);
            jsonObject.put("errcode", 0);
        } catch(APIConnectionException e) {
            logger.error("Connection error. Should retry later. ", e);

        } catch(APIRequestException e) {
            jsonObject.put("errcode", e.getErrorCode());
            jsonObject.put("errmsg", e.getErrorMessage());
            if("1011".equals(e.getErrorCode())){
                logger.error("用户[" + alias + "]在极光没有登记IOS别名,不用放弃处理");
            }else {
                logger.warn("Error response from JPush server. Should review and fix it. " //
                        + "\nHTTP Status: " + e.getStatus()//
                        +"\nError Code: " + e.getErrorCode()//
                        +"\nMsg ID: " + e.getMsgId()//
                        +"\nError Message: " + e.getErrorMessage() +//
                        "\n"+e);
            }
        }
        return jsonObject;
    }


    public static PushPayload buildIosPushObject(String alias, String alert, String msg) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.ios())
                .setAudience(Audience.alias(alias))
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(IosNotification.newBuilder()
                                .setAlert(alert)
                                .setBadge(1)
                                .setSound("default")
//                                .addExtra("from", "JPush")
                                .build())
                        .build())
                .setMessage(Message.content(msg))
                .setOptions(Options.newBuilder()
//                        .setApnsProduction(true) // TODO: 2016/6/13 ios 上线要改成生产环境
                        .build())
                .build();
    }

    public static void main(String[] a){
        sendIosPush("6867266fd0834506bbf0f78c18b484bb","testAlert","testMsg");
    }
}
